/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.xc.hotelmgr.order.common.utils;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ValueOperations<String, String> valueOperations;
    @Autowired
    private HashOperations<String, String, Object> hashOperations;
    @Autowired
    private ListOperations<String, Object> listOperations;
    @Autowired
    private SetOperations<String, Object> setOperations;
    @Autowired
    private ZSetOperations<String, Object> zSetOperations;
    /**  默认过期时长，单位：秒 */
    private final static long DEFAULT_EXPIRE = 60 * 60 * 24;
    /**  不设置过期时长 */
    private final static long NOT_EXPIRE = -1;
    private final static Gson gson = new Gson();

    public void hashSet(String h, String hk, Object value) {
        hashSet(h, hk, value,NOT_EXPIRE);
    }

    public void hashSet(String h, String hk, Object value,long expire) {
        hashOperations.put(h, hk, value);
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(h, expire, TimeUnit.SECONDS);
        }
    }

    public void hashSetAll(String h, Map<? extends String, ?> map) {
        hashSetAll(h, map,NOT_EXPIRE);
    }

    public void hashSetAll(String h, Map<? extends String, ?> map,long expire) {
        hashOperations.putAll(h, map);
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(h, expire, TimeUnit.DAYS);
        }
    }

    public Object hashGet(String h, String hk) {
        return hashOperations.get(h, hk);
    }

    public Long hashDel(String h, String hks) {
        return hashOperations.delete(h, hks);
    }


    public List<Object> hashGetAll(String h, List<String> fields) {
        return  hashOperations.multiGet(h,fields);
    }

    public void set(String key, Object value, long expire){
        valueOperations.set(key, toJson(value));
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }


    public void set(String key, Object value){
        set(key, value, DEFAULT_EXPIRE);
    }

    /**
     * 集合添加数据
     * @param k
     * @param values
     * @return
     */
    public Long addSet(String k, Object... values) {
        return redisTemplate.opsForSet().add(k, values);
    }

    /**
     * 获取集合的所有数据
     * @param k
     * @return
     */
    public <T> T getSet(String k, Class<T> clazz) {
        return (T) redisTemplate.opsForSet().members(k);
    }

    /**
     * 集合删除数据
     * @param k
     * @param values
     * @return
     */
    public Long remove(String k, Object... values) {
        return redisTemplate.opsForSet().remove(k, values);
    }

    /**
     * 判断是否存在集合中
     * @param k
     * @param value
     * @return
     */
    public boolean exist(String k, Object value) {
        return redisTemplate.opsForSet().isMember(k, value);
    }

    /**
     * 判断是否在hash的filed中
     * @param k
     * @param value
     * @return
     */
    public boolean hashExistFiled(String k, Object value) {
        return hashOperations.hasKey(k,value);
    }

    /**
     * 求差集
     * @param
     * @param k
     * @return
     */
    public Set<Object> difference(String k, String otherK) {
        return redisTemplate.opsForSet().difference(k, otherK);
    }

    /**
     * 将数据放入set缓存
     * @param key 键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object...values) {
        try {
            return setOperations.add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public <T> T get(String key, Class<T> clazz, long expire) {
        String value = valueOperations.get(key);
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value == null ? null : fromJson(value, clazz);
    }

    public <T> T get(String key, Class<T> clazz) {
        return get(key, clazz, NOT_EXPIRE);
    }

    public String get(String key, long expire) {
        String value = valueOperations.get(key);
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value;
    }

    public String get(String key) {
        return get(key, NOT_EXPIRE);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    /**
     * Object转成JSON数据
     */
    private String toJson(Object object){
        if(object instanceof Integer || object instanceof Long || object instanceof Float ||
                object instanceof Double || object instanceof Boolean || object instanceof String){
            return String.valueOf(object);
        }
        return gson.toJson(object);
    }

    /**
     * JSON数据，转成Object
     */
    private <T> T fromJson(String json, Class<T> clazz){
        return gson.fromJson(json, clazz);
    }

//    public void setRpsByPipeline(List<RPS> rPSs){
//        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
//        connection.openPipeline();
//        Date priceDate = null;
//        String curDateStr = DateUtils.format(new Date(),"yyyy-MM-dd");
//        Date curDate = DateUtils.stringToDate(curDateStr,"yyyy-MM-dd");
//        Long expire = 0L;
//        String h = "";
//        Map<byte[],byte[]> map = null;
//        for(RPS rPS : rPSs){
//            priceDate = rPS.getPriceDate();
//            //计算价量态失效时间
//            expire = (DateUtils.suDates(priceDate,curDate) + 1)*24*60*60*1000;
//            map = new HashMap<>();
//            map.put("p".getBytes(), rPS.getPrice().toString().getBytes());
//            map.put("n".getBytes(), rPS.getSaleNum().toString().getBytes());
//            h = Constant.RedisKey.RPS_PREFIX.getValue()+ rPS.getId();
//            connection.hMSet(h.getBytes(),map);
//            connection.pExpire(h.getBytes(),expire);
//        }
//        connection.closePipeline();
//    }

}
